package com.idp.web.test.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.amazon.items.ListOrderItems;
import com.amazon.items.Orderitems;
import com.amazon.list.GetOrdersList;
import com.amazon.list.Order;
import com.amazon.list.OrderTotal;
import com.amazonservices.mws.client.MwsUtl;
import com.amazonservices.mws.orders._2013_09_01.MarketplaceWebServiceOrders;
import com.amazonservices.mws.orders._2013_09_01.MarketplaceWebServiceOrdersClient;
import com.amazonservices.mws.orders._2013_09_01.MarketplaceWebServiceOrdersException;
import com.amazonservices.mws.orders._2013_09_01.model.GetOrderRequest;
import com.amazonservices.mws.orders._2013_09_01.model.GetOrderResponse;
import com.amazonservices.mws.orders._2013_09_01.model.ListOrderItemsRequest;
import com.amazonservices.mws.orders._2013_09_01.model.ListOrderItemsResponse;
import com.amazonservices.mws.orders._2013_09_01.model.ListOrdersRequest;
import com.amazonservices.mws.orders._2013_09_01.model.ListOrdersResponse;
import com.amazonservices.mws.orders._2013_09_01.model.ResponseHeaderMetadata;
import com.amazonservices.mws.orders._2013_09_01.samples.MarketplaceWebServiceOrdersSampleConfig;
import com.idp.common.base.BaseController;
import com.idp.common.model.KdniaoJsonBean;
import com.idp.common.model.Trace;
import com.idp.common.util.ValidateUtils;
import com.idp.web.system.entity.SysOrg;
import com.idp.web.test.dao.DeliverGoodsDao;
import com.idp.web.test.dao.OrdertDao;
import com.idp.web.test.entity.Account;
import com.idp.web.test.entity.Amazonorderslists;
import com.idp.web.test.entity.DeliverGoods;
import com.idp.web.test.entity.itemsProduct;
import com.idp.web.test.service.AccountService;
import com.idp.web.test.service.AmazonorderslistsService;
import com.idp.web.test.service.DeliverGoodsService;
import com.idp.web.test.service.LogisticsInfoSearchService;

import cn.creditharmony.loan.util.Xml2JsonUtil;
import net.sf.json.JSONObject;

/**
 * 
 * Amazon订单导出Excelcontroller
 * 
 * <pre>
 * 	历史记录：
 * 	2017-06-15 LiCongCong
 * 	新建文件
 * </pre>
 * 
 * @author
 * 
 * 		<pre>
 * SD
 * 	LiCongCong
 * PG
 *	LiCongCong
 * UT
 *
 * MA
 *         </pre>
 * 
 * @version $Rev$
 *
 *          <p/>
 *          $Id$
 *
 */
@Controller
@RequestMapping("/amazonorderslists")
public class AmazonorderslistsController extends BaseController {

	private Logger logger = Logger.getLogger(AmazonorderslistsController.class);

	@Resource
	private AmazonorderslistsService amazonorderslistsService;

	@Resource
	private LogisticsInfoSearchService logisticsInfoSearchService;

	@Resource
	private DeliverGoodsService deliverGoodsService;
	
	@Resource
	private AccountService accountService;

	@Resource
	private OrdertDao ordertDao;

	@Resource
	private DeliverGoodsDao deliverGoodsDao;

	private List<Amazonorderslists> olist;

	public List<Amazonorderslists> getOlist() {
		return olist;
	}

	public void setOlist(List<Amazonorderslists> olist) {
		this.olist = olist;
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-15 LiCongCong
	 * 	初始化查询页面
	 * </pre>
	 * 
	 * @return
	 */
	@RequestMapping("/init")
	public String init() {

		return "shopping/Amazon/ordertSearch";
	}

	@RequestMapping("/initAmazon")
	public String initAmazon() {

		return "shopping/AmazonDatabase/ordertSearch";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-15 LiCongCong
	 * 	分页查询
	 * </pre>
	 * 
	 * @param amazonorderslists
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Amazonorderslists amazonorderslists, PageController<Amazonorderslists> page,
			HttpServletRequest requestParam) {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		date = calendar.getTime();

		String startDate = requestParam.getParameter("start");
		String endDate = requestParam.getParameter("end");
		String orderStatusT = requestParam.getParameter("status");

		if (startDate == null || startDate == "") {
			startDate = df.format(date);
		}

		if (endDate == null || endDate == "") {
			endDate = df.format(new Date());
		}

		System.err.println(startDate + "," + endDate);
		String[] starts = startDate.split("-");
		String startYear = starts[0];
		String startMonth = starts[1];
		String startDay = starts[2];

		String[] ends = endDate.split("-");
		String endYear = ends[0];
		String endMonth = ends[1];
		String endDay = ends[2];

		try {

			MarketplaceWebServiceOrdersClient client = MarketplaceWebServiceOrdersSampleConfig.getClient();
			// Create a request.ListOrdersRequest
			ListOrdersRequest request = new ListOrdersRequest();
			String sellerId = "A31FK1YOBVUT0K";
			request.setSellerId(sellerId);
			String mwsAuthToken = "example";
			request.setMWSAuthToken(mwsAuthToken);
			XMLGregorianCalendar createdAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
			createdAfter.setYear(Integer.parseInt(startYear));
			createdAfter.setMonth(Integer.parseInt(startMonth));
			createdAfter.setDay(Integer.parseInt(startDay));
			request.setCreatedAfter(createdAfter);
			XMLGregorianCalendar createdBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
			createdBefore.setYear(Integer.parseInt(endYear));
			createdBefore.setMonth(Integer.parseInt(endMonth));
			createdBefore.setDay(Integer.parseInt(endDay));
			request.setCreatedBefore(createdBefore);
			XMLGregorianCalendar lastUpdatedAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
			request.setLastUpdatedAfter(lastUpdatedAfter);
			XMLGregorianCalendar lastUpdatedBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
			request.setLastUpdatedBefore(lastUpdatedBefore);
			List<String> orderStatus = new ArrayList<String>();
			if (orderStatusT == null || orderStatusT.equals("all")) {
				System.out.println("请求全部数据");
			} else {

				if (orderStatusT.equals("Unshipped")) {
					orderStatus.add("Unshipped");
					orderStatus.add("PartiallyShipped");
				} else {
					orderStatus.add(orderStatusT);
				}

			}
			request.setOrderStatus(orderStatus);
			List<String> marketplaceId = new ArrayList<String>();
			marketplaceId.add("A2EUQ1WTGCTBG2");
			marketplaceId.add("ATVPDKIKX0DER");
			marketplaceId.add("A1AM78C64UM0Y8");
			request.setMarketplaceId(marketplaceId);
			List<String> fulfillmentChannel = new ArrayList<String>();
			request.setFulfillmentChannel(fulfillmentChannel);
			List<String> paymentMethod = new ArrayList<String>();
			request.setPaymentMethod(paymentMethod);
			String buyerEmail = "";
			request.setBuyerEmail(buyerEmail);
			String sellerOrderId = "";
			request.setSellerOrderId(sellerOrderId);
			Integer maxResultsPerPage = 100;
			request.setMaxResultsPerPage(maxResultsPerPage);
			List<String> tfmShipmentStatus = new ArrayList<String>();
			request.setTFMShipmentStatus(tfmShipmentStatus);

			ListOrdersResponse response = invokeListOrders(client, request);
			requestParam.setAttribute("startDate", startDate);
			requestParam.setAttribute("endDate", endDate);

			if (response == null) {

				return "shopping/Amazon/ListErr";
			}

			String responseXml = response.toXML();
			System.out.println(responseXml);

			String jsonstr = Xml2JsonUtil.xml2JSON(responseXml);

			GetOrdersList getO = JSON.parseObject(jsonstr, GetOrdersList.class);

			if (getO.getListOrdersResponse().getListOrdersResult().get(0).getOrders() == null) {

				return "shopping/Amazon/ListNull";

			}

			List<Order> orderlist = getO.getListOrdersResponse().getListOrdersResult().get(0).getOrders().get(0)
					.getOrder();

			System.out.println(orderlist.size());

			List<Amazonorderslists> olist = new ArrayList<Amazonorderslists>();

			try {

				if (orderlist.size() == 0) {
					System.out.println("null list");
				} else {

					for (Order o : orderlist) {

						if (o.getAmazonOrderId() == null) {
							System.out.println("所有订单已导出完成！");
						} else {

							amazonorderslists = new Amazonorderslists();
							amazonorderslists.setOrderid(o.getAmazonOrderId().get(0));
							amazonorderslists
									.setOrderstatus(o.getOrderStatus() == null ? "" : o.getOrderStatus().get(0));
							amazonorderslists.setPurchasedate(o.getPurchaseDate() == null ? ""
									: o.getPurchaseDate().toString().substring(2,
											o.getPurchaseDate().toString().length() - 2));
							amazonorderslists.setBuyeremail(o.getBuyerEmail() == null ? "" : o.getBuyerEmail().get(0));
							amazonorderslists.setCurrency(
									o.getOrderTotal() == null ? "" : o.getOrderTotal().get(0).getCurrencyCode().get(0));
							amazonorderslists.setShipservicelevel(
									o.getShipServiceLevel() == null ? "" : o.getShipServiceLevel().get(0));
							amazonorderslists.setRecipientname(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getName().get(0));
							/*
							 * amazonorderslists.setShipaddress1(o.
							 * getShippingAddress() == null ? "" :
							 * o.getShippingAddress().get(0).getAddressLine1().
							 * get(0));
							 */
							amazonorderslists.setShipcity(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getCity().get(0));
							amazonorderslists.setShipstate(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getStateOrRegion().get(0));
							amazonorderslists.setShippostalcode(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getPostalCode().get(0));
							amazonorderslists.setShipcountry(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getCountryCode().get(0));
							amazonorderslists.setDeliverystartdate(o.getEarliestDeliveryDate() == null ? ""
									: o.getEarliestDeliveryDate().toString().substring(2,
											o.getEarliestDeliveryDate().toString().length() - 2));
							amazonorderslists.setDeliveryenddate(o.getLatestDeliveryDate() == null ? ""
									: o.getLatestDeliveryDate().toString().substring(2,
											o.getLatestDeliveryDate().toString().length() - 2));
							amazonorderslists
									.setSaleschannel(o.getSalesChannel() == null ? "" : o.getSalesChannel().get(0));
							amazonorderslists.setIsbusinessorder(
									o.getIsBusinessOrder() == null ? "" : o.getIsBusinessOrder().get(0));
							amazonorderslists.setPricedesignation(
									o.getOrderTotal() == null ? "" : o.getOrderTotal().get(0).getAmount().get(0));
							amazonorderslists.setIsprime(o.getIsPrime() == null ? "" : o.getIsPrime().get(0));
							amazonorderslists.setQuantitypurchased(
									o.getOrderTotal() == null ? "0" : o.getOrderTotal().size() + "");

							if (o.getOrderTotal() == null) {

								amazonorderslists.setItemprice("0");
							} else {

								if (o.getOrderTotal().size() > 1) {
									Double sum = 0.0;
									for (OrderTotal s : o.getOrderTotal()) {
										sum = sum + Double.valueOf(s.getAmount().get(0));
									}
									amazonorderslists.setItemprice(sum + "");
								} else {
									amazonorderslists.setItemprice(o.getOrderTotal().size() > 0
											? o.getOrderTotal().get(0).getAmount().get(0) : "0");
								}

							}

							olist.add(amazonorderslists);

						}

					}

				}

			} catch (Exception e) {

				logger.error(e.getMessage(), e);
			}

			setOlist(olist);
			page.setResult(olist);
			page.setTotalCount(olist.size());
			page.setTotalPages(olist.size() % 10 == 0 ? olist.size() / 10 : olist.size() / 10 + 1);
			requestParam.setAttribute("page", page);
			requestParam.setAttribute("begin", 0);
			requestParam.setAttribute("end", 10);

		} catch (Exception e) {

			logger.error(e.getMessage(), e);
		}

		return "shopping/Amazon/ordertList";
	}

	public List<Amazonorderslists> synchronization(String startDate, String endDate,Integer accountid) {
		JSONObject json = new JSONObject();

		System.err.println(startDate + "," + endDate);
		String[] starts = startDate.split("-");
		String startYear = starts[0];
		String startMonth = starts[1];
		String startDay = starts[2];

		String[] ends = endDate.split("-");
		String endYear = ends[0];
		String endMonth = ends[1];
		String endDay = ends[2];
		
		String sellerId = "A31FK1YOBVUT0K";
		String marketno="ATVPDKIKX0DER";
		if(accountid!=null){
			
			Account account=accountService.getById(accountid);
			sellerId =account.getOrderApi();
			marketno=account.getShelvesApi();
		}

		
		System.err.println("传入商家id="+sellerId+",商城编号="+marketno);

		try {

			MarketplaceWebServiceOrdersClient client = MarketplaceWebServiceOrdersSampleConfig.getClient();
			ListOrdersRequest request = new ListOrdersRequest();		
			request.setSellerId(sellerId);
			String mwsAuthToken = "example";
			request.setMWSAuthToken(mwsAuthToken);
			XMLGregorianCalendar createdAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
			createdAfter.setYear(Integer.parseInt(startYear));
			createdAfter.setMonth(Integer.parseInt(startMonth));
			createdAfter.setDay(Integer.parseInt(startDay));
			request.setCreatedAfter(createdAfter);
			XMLGregorianCalendar createdBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
			createdBefore.setYear(Integer.parseInt(endYear));
			createdBefore.setMonth(Integer.parseInt(endMonth));
			createdBefore.setDay(Integer.parseInt(endDay));
			request.setCreatedBefore(createdBefore);
			XMLGregorianCalendar lastUpdatedAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
			request.setLastUpdatedAfter(lastUpdatedAfter);
			XMLGregorianCalendar lastUpdatedBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
			request.setLastUpdatedBefore(lastUpdatedBefore);
			List<String> orderStatus = new ArrayList<String>();
			request.setOrderStatus(orderStatus);
			List<String> marketplaceId = new ArrayList<String>();
			marketplaceId.add(marketno);
//			marketplaceId.add("A2EUQ1WTGCTBG2");
//			marketplaceId.add("ATVPDKIKX0DER");
//			marketplaceId.add("A1AM78C64UM0Y8");
			request.setMarketplaceId(marketplaceId);
			List<String> fulfillmentChannel = new ArrayList<String>();
			request.setFulfillmentChannel(fulfillmentChannel);
			List<String> paymentMethod = new ArrayList<String>();
			request.setPaymentMethod(paymentMethod);
			String buyerEmail = "";
			request.setBuyerEmail(buyerEmail);
			String sellerOrderId = "";
			request.setSellerOrderId(sellerOrderId);
			Integer maxResultsPerPage = 100;
			request.setMaxResultsPerPage(maxResultsPerPage);
			List<String> tfmShipmentStatus = new ArrayList<String>();
			request.setTFMShipmentStatus(tfmShipmentStatus);

			ListOrdersResponse response = invokeListOrders(client, request);

			if (response == null) {

				return null;
			}

			String responseXml = response.toXML();
			System.out.println(responseXml);

			String jsonstr = Xml2JsonUtil.xml2JSON(responseXml);

			GetOrdersList getO = JSON.parseObject(jsonstr, GetOrdersList.class);

			if (getO.getListOrdersResponse().getListOrdersResult().get(0).getOrders() == null) {

				return null;

			}

			List<Order> orderlist = getO.getListOrdersResponse().getListOrdersResult().get(0).getOrders().get(0)
					.getOrder();

			System.out.println(orderlist.size());

			List<Amazonorderslists> olist = new ArrayList<Amazonorderslists>();

			try {

				if (orderlist.size() == 0) {
					System.out.println("null list");
				} else {

					for (Order o : orderlist) {

						if (o.getAmazonOrderId() == null) {
							System.out.println("所有订单已导出完成！");
						} else {

							Amazonorderslists amazonorderslists = new Amazonorderslists();
							amazonorderslists.setOrderid(o.getAmazonOrderId().get(0));
							amazonorderslists
									.setOrderstatus(o.getOrderStatus() == null ? "" : o.getOrderStatus().get(0));
							amazonorderslists.setPurchasedate(o.getPurchaseDate() == null ? ""
									: o.getPurchaseDate().toString().substring(2,
											o.getPurchaseDate().toString().length() - 2));
							amazonorderslists.setBuyeremail(o.getBuyerEmail() == null ? "" : o.getBuyerEmail().get(0));
							amazonorderslists.setCurrency(
									o.getOrderTotal() == null ? "" : o.getOrderTotal().get(0).getCurrencyCode().get(0));
							amazonorderslists.setShipservicelevel(
									o.getShipServiceLevel() == null ? "" : o.getShipServiceLevel().get(0));
							amazonorderslists.setRecipientname(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getName().get(0));
							/*
							 * amazonorderslists.setShipaddress1(o.
							 * getShippingAddress() == null ? "" :
							 * o.getShippingAddress().get(0).getAddressLine1().
							 * get(0));
							 */
							amazonorderslists.setShipcity(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getCity().get(0));
							amazonorderslists.setShipstate(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getStateOrRegion().get(0));
							amazonorderslists.setShippostalcode(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getPostalCode().get(0));
							amazonorderslists.setShipcountry(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getCountryCode().get(0));
							amazonorderslists.setDeliverystartdate(o.getEarliestDeliveryDate() == null ? ""
									: o.getEarliestDeliveryDate().toString().substring(2,
											o.getEarliestDeliveryDate().toString().length() - 2));
							amazonorderslists.setDeliveryenddate(o.getLatestDeliveryDate() == null ? ""
									: o.getLatestDeliveryDate().toString().substring(2,
											o.getLatestDeliveryDate().toString().length() - 2));
							amazonorderslists
									.setSaleschannel(o.getSalesChannel() == null ? "" : o.getSalesChannel().get(0));
							amazonorderslists.setIsbusinessorder(
									o.getIsBusinessOrder() == null ? "" : o.getIsBusinessOrder().get(0));
							amazonorderslists.setPricedesignation(
									o.getOrderTotal() == null ? "" : o.getOrderTotal().get(0).getAmount().get(0));
							amazonorderslists.setIsprime(o.getIsPrime() == null ? "" : o.getIsPrime().get(0));
							amazonorderslists.setQuantitypurchased(
									o.getOrderTotal() == null ? "0" : o.getOrderTotal().size() + "");

							if (o.getOrderTotal() == null) {

								amazonorderslists.setItemprice("0");
							} else {

								if (o.getOrderTotal().size() > 1) {
									Double sum = 0.0;
									for (OrderTotal s : o.getOrderTotal()) {
										sum = sum + Double.valueOf(s.getAmount().get(0));
									}
									amazonorderslists.setItemprice(sum + "");
								} else {
									amazonorderslists.setItemprice(o.getOrderTotal().size() > 0
											? o.getOrderTotal().get(0).getAmount().get(0) : "0");
								}

							}

							olist.add(amazonorderslists);

						}

					}

				}

			} catch (Exception e) {

				logger.error(e.getMessage(), e);
			}

			return olist;

		} catch (Exception e) {

			logger.error(e.getMessage(), e);

		}

		return null;
	}

	@RequestMapping("/synchronization")
	@ResponseBody
	public String synchronizationByTime(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		Integer platformId = 2;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		
		String accountid=request.getParameter("id");

		try {
			Date date = ordertDao.getCreateTimeByPlatformDesc(platformId);

			if (date == null) {

				Date date1 = new Date();
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(date1);
				calendar.add(Calendar.DAY_OF_MONTH, -365);
				date1 = calendar.getTime();

				date = date1;

			}

			Date today = new Date();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(today);
			calendar.add(Calendar.DAY_OF_MONTH, 0);
			today = calendar.getTime();

			String startDate = df.format(date);
			String endDate = df.format(today);
			
			Integer accountidd=2;
			if(accountid!=null){
				accountidd=Integer.parseInt(accountid);
			}

			List<Amazonorderslists> olist = synchronization(startDate, endDate,accountidd);

			if (olist != null) {

				Integer count = amazonorderslistsService.synchronization(olist, platformId,accountidd);
				if (count == 0) {
					json.put("result", "没有新的订单");
					json.put("para", 0);
					json.put("accountid", accountidd);
				} else {
					json.put("result", "同步成功,新增" + count + "条订单");
					json.put("para", 1);
					json.put("accountid", accountidd);
				}

			}

		} catch (Exception e) {

			logger.error(e.getMessage(), e);
			json.put("para", 48);
			json.put("result", "同步失败");
			
		}

		return json.toString();
	}

	public static int daysBetween(Date smdate, Date bdate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	@RequestMapping("/nextPage")
	public String nextTokenPage(PageController<Amazonorderslists> page, HttpServletRequest requestParam) {

		String pageNo = requestParam.getParameter("pageNo");
		int pageNo1 = Integer.parseInt(pageNo);

		int begin = (pageNo1 - 1) * 10;
		int end = begin + 10;
		page.setResult(getOlist());
		page.setPageNo(pageNo1);
		page.setTotalCount(getOlist().size());
		page.setTotalPages(getOlist().size() % 10 == 0 ? getOlist().size() / 10 : getOlist().size() / 10 + 1);
		requestParam.setAttribute("page", page);
		requestParam.setAttribute("begin", begin);
		requestParam.setAttribute("end", end);

		return "shopping/Amazon/ordertList";
	}

	@RequestMapping("/listTen")
	public String listTen(HttpServletRequest requestParam) {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		date = calendar.getTime();

		String startDate = requestParam.getParameter("start");
		String endDate = requestParam.getParameter("end");

		if (startDate == null) {
			startDate = df.format(date);
		}

		if (endDate == null) {
			endDate = df.format(new Date());
		}

		System.err.println(startDate + "," + endDate);
		String[] starts = startDate.split("-");
		String startYear = starts[0];
		String startMonth = starts[1];
		String startDay = starts[2];

		String[] ends = endDate.split("-");
		String endYear = ends[0];
		String endMonth = ends[1];
		String endDay = ends[2];

		try {

			MarketplaceWebServiceOrdersClient client = MarketplaceWebServiceOrdersSampleConfig.getClient();
			// Create a request.ListOrdersRequest
			ListOrdersRequest request = new ListOrdersRequest();
			String sellerId = "A31FK1YOBVUT0K";
			request.setSellerId(sellerId);
			String mwsAuthToken = "example";
			request.setMWSAuthToken(mwsAuthToken);
			XMLGregorianCalendar createdAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
			createdAfter.setYear(Integer.parseInt(startYear));
			createdAfter.setMonth(Integer.parseInt(startMonth));
			createdAfter.setDay(Integer.parseInt(startDay));
			request.setCreatedAfter(createdAfter);
			XMLGregorianCalendar createdBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
			createdBefore.setYear(Integer.parseInt(endYear));
			createdBefore.setMonth(Integer.parseInt(endMonth));
			createdBefore.setDay(Integer.parseInt(endDay));
			request.setCreatedBefore(createdBefore);
			XMLGregorianCalendar lastUpdatedAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
			request.setLastUpdatedAfter(lastUpdatedAfter);
			XMLGregorianCalendar lastUpdatedBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
			request.setLastUpdatedBefore(lastUpdatedBefore);
			List<String> orderStatus = new ArrayList<String>();
			request.setOrderStatus(orderStatus);
			List<String> marketplaceId = new ArrayList<String>();
			marketplaceId.add("A2EUQ1WTGCTBG2");
			marketplaceId.add("ATVPDKIKX0DER");
			marketplaceId.add("A1AM78C64UM0Y8");
			request.setMarketplaceId(marketplaceId);
			List<String> fulfillmentChannel = new ArrayList<String>();
			request.setFulfillmentChannel(fulfillmentChannel);
			List<String> paymentMethod = new ArrayList<String>();
			request.setPaymentMethod(paymentMethod);
			String buyerEmail = "";
			request.setBuyerEmail(buyerEmail);
			String sellerOrderId = "";
			request.setSellerOrderId(sellerOrderId);
			Integer maxResultsPerPage = 10;
			request.setMaxResultsPerPage(maxResultsPerPage);
			List<String> tfmShipmentStatus = new ArrayList<String>();
			request.setTFMShipmentStatus(tfmShipmentStatus);

			ListOrdersResponse response = invokeListOrders(client, request);
			if (response == null) {
				System.out.println("nullllllllllllllllllllllllllllllllll");
				return null;
			}

			String responseXml = response.toXML();
			System.out.println(responseXml);

			String jsonstr = Xml2JsonUtil.xml2JSON(responseXml);

			GetOrdersList getO = JSON.parseObject(jsonstr, GetOrdersList.class);

			List<Order> orderlist = getO.getListOrdersResponse().getListOrdersResult().get(0).getOrders().get(0)
					.getOrder();

			List<Amazonorderslists> olist = new ArrayList<Amazonorderslists>();

			try {

				if (orderlist == null) {
					System.out.println("null list");
				} else {

					for (Order o : orderlist) {

						if (o.getAmazonOrderId() == null) {
							System.out.println("所有订单已导出完成！");
						} else {

							Amazonorderslists amazonorderslists = new Amazonorderslists();
							amazonorderslists.setOrderid(o.getAmazonOrderId().get(0));
							amazonorderslists
									.setOrderstatus(o.getOrderStatus() == null ? "" : o.getOrderStatus().get(0));
							amazonorderslists.setPurchasedate(o.getPurchaseDate() == null ? ""
									: o.getPurchaseDate().toString().substring(2,
											o.getPurchaseDate().toString().length() - 2));
							amazonorderslists.setBuyeremail(o.getBuyerEmail() == null ? "" : o.getBuyerEmail().get(0));
							amazonorderslists.setCurrency(
									o.getOrderTotal() == null ? "" : o.getOrderTotal().get(0).getCurrencyCode().get(0));
							amazonorderslists.setShipservicelevel(
									o.getShipServiceLevel() == null ? "" : o.getShipServiceLevel().get(0));
							amazonorderslists.setRecipientname(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getName().get(0));
							amazonorderslists.setShipaddress1(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getAddressLine1().get(0));
							amazonorderslists.setShipcity(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getCity().get(0));
							amazonorderslists.setShipstate(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getStateOrRegion().get(0));
							amazonorderslists.setShippostalcode(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getPostalCode().get(0));
							amazonorderslists.setShipcountry(o.getShippingAddress() == null ? ""
									: o.getShippingAddress().get(0).getCountryCode().get(0));
							amazonorderslists.setDeliverystartdate(o.getEarliestDeliveryDate() == null ? ""
									: o.getEarliestDeliveryDate().toString().substring(2,
											o.getEarliestDeliveryDate().toString().length() - 2));
							amazonorderslists.setDeliveryenddate(o.getLatestDeliveryDate() == null ? ""
									: o.getLatestDeliveryDate().toString().substring(2,
											o.getLatestDeliveryDate().toString().length() - 2));
							amazonorderslists
									.setSaleschannel(o.getSalesChannel() == null ? "" : o.getSalesChannel().get(0));
							amazonorderslists.setIsbusinessorder(
									o.getIsBusinessOrder() == null ? "" : o.getIsBusinessOrder().get(0));
							amazonorderslists.setPricedesignation(
									o.getOrderTotal() == null ? "" : o.getOrderTotal().get(0).getAmount().get(0));
							amazonorderslists.setIsprime(o.getIsPrime() == null ? "" : o.getIsPrime().get(0));

							olist.add(amazonorderslists);

						}

					}

				}

			} catch (Exception e) {

				logger.error(e.getMessage(), e);
			}

			requestParam.setAttribute("orderlist", olist);

		} catch (Exception e) {

			logger.error(e.getMessage(), e);
		}

		return "shopping/Amazon/ordertList";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-15 LiCongCong
	 * 	新增修改页面初始化
	 * </pre>
	 * 
	 * @param id
	 * @param request
	 * @return
	 */

	@RequestMapping("/orderDetails")
	public String orderDetails(HttpServletRequest request) {

		String orderid = request.getParameter("orderid");

		System.err.println(orderid);

		MarketplaceWebServiceOrdersClient client = MarketplaceWebServiceOrdersSampleConfig.getClient();

		ListOrderItemsRequest request2 = new ListOrderItemsRequest();
		String sellerId = "A31FK1YOBVUT0K";
		request2.setSellerId(sellerId);
		request2.setAmazonOrderId(orderid);
		ListOrderItemsResponse itemsresponse = invokeListOrderItems(client, request2);

		GetOrderRequest request1 = new GetOrderRequest();
		request1.setSellerId(sellerId);
		List<String> amazonOrderId1 = new ArrayList<String>();
		amazonOrderId1.add(orderid);
		request1.setAmazonOrderId(amazonOrderId1);
		GetOrderResponse response = invokeGetOrder(client, request1);
		String responseXml = response.toXML();
		String jsonstr = Xml2JsonUtil.xml2JSON(responseXml);

		com.amazonOrder.get.AmazonOrder a = JSON.parseObject(jsonstr, com.amazonOrder.get.AmazonOrder.class);
		com.amazonOrder.get.Order ord = a.getGetorderresponse().getGetorderresult().get(0).getOrders().get(0).getOrder()
				.get(0);

		String jsonstr2 = itemsresponse.toJSON();
		ListOrderItems listOrderItems = JSON.parseObject(jsonstr2, ListOrderItems.class);
		List<Orderitems> orderitemsList = listOrderItems.getListorderitemsresult().getOrderitems();

		List<itemsProduct> itplist = new ArrayList<itemsProduct>();
		itemsProduct itemsP = new itemsProduct();
		for (Orderitems oditems : orderitemsList) {

			itemsP.setProductName(oditems.getTitle());
			itemsP.setProductSKU(oditems.getSellersku());
			itemsP.setUnitprice(oditems.getItemprice() == null ? "未知" : oditems.getItemprice().getAmount());
			itemsP.setQuanity(oditems.getQuantityordered() + "");
			itemsP.setCurrentinventory("");
			itemsP.setShipSKU(oditems.getSellersku());
			double unitp = Double
					.parseDouble(oditems.getItemprice() == null ? "0" : oditems.getItemprice().getAmount());
			int qt = oditems.getQuantityordered();
			itemsP.setSumPrice(unitp * qt + "");
			itplist.add(itemsP);
		}

		Amazonorderslists amazonorderslists = new Amazonorderslists();
		amazonorderslists.setOrderid(ord.getAmazonorderid() == null ? "未知" : ord.getAmazonorderid().get(0));
		amazonorderslists.setOrderstatus(ord.getOrderstatus() == null ? "未知" : ord.getOrderstatus().get(0));
		amazonorderslists.setPurchasedate(ord.getPurchasedate() == null ? "未下单"
				: ord.getPurchasedate().toString().substring(2, ord.getPurchasedate().toString().length() - 2));
		amazonorderslists.setPaymentsdate(ord.getPurchasedate() == null ? "未下单"
				: ord.getPurchasedate().toString().substring(2, ord.getPurchasedate().toString().length() - 2));
		amazonorderslists.setDeliverystartdate(ord.getEarliestshipdate() == null ? "未发货"
				: ord.getEarliestshipdate().toString().substring(2, ord.getEarliestshipdate().toString().length() - 2));
		amazonorderslists
				.setItemprice(ord.getOrdertotal() == null ? "未知" : ord.getOrdertotal().get(0).getAmount().get(0));

		amazonorderslists.setShippingprice("未知");
		amazonorderslists.setPricedesignation(
				ord.getOrdertotal() == null ? "未知" : ord.getOrdertotal().get(0).getAmount().get(0));

		amazonorderslists.setRecipientname(
				ord.getShippingaddress() == null ? "未知" : ord.getShippingaddress().get(0).getName().get(0));
		amazonorderslists.setShipaddress1(ord.getShippingaddress() == null ? "未知"
				: ord.getShippingaddress().get(0).getCountrycode().toString().substring(1,
						ord.getShippingaddress().get(0).getCountrycode().toString().length() - 1)
						+ ","
						+ ord.getShippingaddress().get(0).getStateorregion().toString().substring(1,
								ord.getShippingaddress().get(0).getStateorregion().toString().length() - 1)
						+ ","
						+ ord.getShippingaddress().get(0).getCity().toString().substring(1,
								ord.getShippingaddress().get(0).getCity().toString().length() - 1)
						+ "," + ord.getShippingaddress().get(0).getAddressline1().get(0));
		/*
		 * amazonorderslists.setBuyerphonenumber( ord.getShippingaddress() ==
		 * null ? "未知" : ord.getShippingaddress().get(0).getPhone().get(0));
		 */
		amazonorderslists.setShippostalcode(
				ord.getShippingaddress() == null ? "未知" : ord.getShippingaddress().get(0).getPostalcode().get(0));
		amazonorderslists.setDeliverystartdate(ord.getShippingaddress() == null ? "未知"
				: ord.getEarliestshipdate().toString().substring(2, ord.getEarliestshipdate().toString().length() - 2));

		request.setAttribute("ord", amazonorderslists);
		request.setAttribute("itemsList", itplist);

		return "shopping/Amazon/amazonOrderDetail";
	}

	@RequestMapping("/amazonorderslists")
	public String amazonorderslists(Integer id, HttpServletRequest request) {

		try {

			if (ValidateUtils.isNotEmpty(id)) {

				Amazonorderslists amazonorderslists = amazonorderslistsService.getById(id);
				request.setAttribute("amazonorderslists", amazonorderslists);
			}
		} catch (Exception e) {

			logger.error(e.getMessage(), e);
		}

		return "shopping/getExcel/amazonorderslists";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-15 LiCongCong
	 * 	保存
	 * </pre>
	 * 
	 * @param amazonorderslists
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public String save(Amazonorderslists amazonorderslists) {

		JSONObject json = new JSONObject();

		try {

			// 修改
			if (ValidateUtils.isNotEmpty(amazonorderslists.getId())) {

				amazonorderslistsService.update(amazonorderslists);
			}
			// 新增
			else {

				amazonorderslistsService.add(amazonorderslists);
			}
			json.put("result", "save_success");
		} catch (Exception e) {

			logger.error(e.getMessage(), e);
			json.put("result", "save_fail");
		}

		return json.toString();
	}

	@RequestMapping("/insertdata")
	public List<Order> insertdata(HttpServletRequest requestParam) {

		MarketplaceWebServiceOrdersClient client = MarketplaceWebServiceOrdersSampleConfig.getClient();

		// Create a request.ListOrdersRequest
		ListOrdersRequest request = new ListOrdersRequest();
		String sellerId = "A31FK1YOBVUT0K";
		request.setSellerId(sellerId);
		String mwsAuthToken = "example";
		request.setMWSAuthToken(mwsAuthToken);
		XMLGregorianCalendar createdAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
		createdAfter.setYear(2017);
		createdAfter.setMonth(5);
		createdAfter.setDay(1);
		request.setCreatedAfter(createdAfter);
		XMLGregorianCalendar createdBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
		createdBefore.setYear(2017);
		createdBefore.setMonth(6);
		createdBefore.setDay(16);
		request.setCreatedBefore(createdBefore);
		XMLGregorianCalendar lastUpdatedAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
		request.setLastUpdatedAfter(lastUpdatedAfter);
		XMLGregorianCalendar lastUpdatedBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
		request.setLastUpdatedBefore(lastUpdatedBefore);
		List<String> orderStatus = new ArrayList<String>();
		request.setOrderStatus(orderStatus);
		List<String> marketplaceId = new ArrayList<String>();
		marketplaceId.add("A2EUQ1WTGCTBG2");
		marketplaceId.add("ATVPDKIKX0DER");
		marketplaceId.add("A1AM78C64UM0Y8");
		request.setMarketplaceId(marketplaceId);
		List<String> fulfillmentChannel = new ArrayList<String>();
		request.setFulfillmentChannel(fulfillmentChannel);
		List<String> paymentMethod = new ArrayList<String>();
		request.setPaymentMethod(paymentMethod);
		String buyerEmail = "";
		request.setBuyerEmail(buyerEmail);
		String sellerOrderId = "";
		request.setSellerOrderId(sellerOrderId);
		Integer maxResultsPerPage = 50;
		request.setMaxResultsPerPage(maxResultsPerPage);
		List<String> tfmShipmentStatus = new ArrayList<String>();
		request.setTFMShipmentStatus(tfmShipmentStatus);

		ListOrdersResponse response = invokeListOrders(client, request);

		String responseXml = response.toXML();
		System.out.println(responseXml);

		String jsonstr = Xml2JsonUtil.xml2JSON(responseXml);
		/*
		 * ExcelFileUtil excel = new ExcelFileUtil();
		 * 
		 * System.out.println(jsonstr);
		 */

		GetOrdersList getO = JSON.parseObject(jsonstr, GetOrdersList.class);

		List<Order> orderlist = getO.getListOrdersResponse().getListOrdersResult().get(0).getOrders().get(0).getOrder();

		Amazonorderslists amazonorderslists = new Amazonorderslists();

		try {

			if (orderlist == null) {
				System.out.println("null list");
			} else {

				System.out.println(orderlist.size());

				for (Order o : orderlist) {

					if (o.getAmazonOrderId() == null) {
						System.out.println("所有订单已导出完成！");
					} else {

						amazonorderslists.setOrderid(o.getAmazonOrderId().get(0));
						amazonorderslists.setPurchasedate(o.getPurchaseDate() == null ? ""
								: o.getPurchaseDate().toString().substring(2,
										o.getPurchaseDate().toString().length() - 2));
						amazonorderslists.setBuyeremail(o.getBuyerEmail() == null ? "" : o.getBuyerEmail().get(0));
						amazonorderslists.setCurrency(
								o.getOrderTotal() == null ? "" : o.getOrderTotal().get(0).getCurrencyCode().get(0));
						amazonorderslists.setShipservicelevel(
								o.getShipServiceLevel() == null ? "" : o.getShipServiceLevel().get(0));
						amazonorderslists.setRecipientname(
								o.getShippingAddress() == null ? "" : o.getShippingAddress().get(0).getName().get(0));
						amazonorderslists.setShipaddress1(o.getShippingAddress() == null ? ""
								: o.getShippingAddress().get(0).getAddressLine1().get(0));
						amazonorderslists.setShipcity(
								o.getShippingAddress() == null ? "" : o.getShippingAddress().get(0).getCity().get(0));
						amazonorderslists.setShipstate(o.getShippingAddress() == null ? ""
								: o.getShippingAddress().get(0).getStateOrRegion().get(0));
						amazonorderslists.setShippostalcode(o.getShippingAddress() == null ? ""
								: o.getShippingAddress().get(0).getPostalCode().get(0));
						amazonorderslists.setShipcountry(o.getShippingAddress() == null ? ""
								: o.getShippingAddress().get(0).getCountryCode().get(0));
						amazonorderslists.setDeliverystartdate(o.getEarliestDeliveryDate() == null ? ""
								: o.getEarliestDeliveryDate().toString().substring(2,
										o.getEarliestDeliveryDate().toString().length() - 2));
						amazonorderslists.setDeliveryenddate(o.getLatestDeliveryDate() == null ? ""
								: o.getLatestDeliveryDate().toString().substring(2,
										o.getLatestDeliveryDate().toString().length() - 2));
						amazonorderslists
								.setSaleschannel(o.getSalesChannel() == null ? "" : o.getSalesChannel().get(0));
						amazonorderslists.setIsbusinessorder(
								o.getIsBusinessOrder() == null ? "" : o.getIsBusinessOrder().get(0));
						amazonorderslists.setPricedesignation(
								o.getOrderTotal() == null ? "" : o.getOrderTotal().get(0).getAmount().get(0));
						amazonorderslists.setIsprime(o.getIsPrime() == null ? "" : o.getIsPrime().get(0));

						amazonorderslistsService.add(amazonorderslists);

					}

				}

			}

		} catch (Exception e) {

			logger.error(e.getMessage(), e);
		}

		return orderlist;
	}

	@RequestMapping("/getThisOrderInfo")
	public static void getThisOrderInfo(String orderId) {

		MarketplaceWebServiceOrdersClient client = MarketplaceWebServiceOrdersSampleConfig.getClient();
		GetOrderRequest request = new GetOrderRequest();
		String sellerId = "A31FK1YOBVUT0K";
		request.setSellerId(sellerId);
		List<String> amazonOrderId = new ArrayList<String>();
		amazonOrderId.add(orderId);
		request.setAmazonOrderId(amazonOrderId);
		GetOrderResponse response = invokeGetOrder(client, request);
		String responseXml = response.toXML();
		String jsonstr = Xml2JsonUtil.xml2JSON(responseXml);

		com.amazonOrder.get.AmazonOrder a = JSON.parseObject(jsonstr, com.amazonOrder.get.AmazonOrder.class);
		com.amazonOrder.get.Order ord = a.getGetorderresponse().getGetorderresult().get(0).getOrders().get(0).getOrder()
				.get(0);

	}

	public static GetOrderResponse invokeGetOrder(MarketplaceWebServiceOrders client, GetOrderRequest request) {
		try {
			// Call the service.
			GetOrderResponse response = client.getOrder(request);
			ResponseHeaderMetadata rhmd = response.getResponseHeaderMetadata();
			// We recommend logging every the request id and timestamp of every
			// call.
			System.out.println("Response:");
			System.out.println("RequestId: " + rhmd.getRequestId());
			System.out.println("Timestamp: " + rhmd.getTimestamp());

			return response;
		} catch (MarketplaceWebServiceOrdersException ex) {
			// Exception properties are important for diagnostics.
			System.out.println("Service Exception:");
			ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
			if (rhmd != null) {
				System.out.println("RequestId: " + rhmd.getRequestId());
				System.out.println("Timestamp: " + rhmd.getTimestamp());
			}
			System.out.println("Message: " + ex.getMessage());
			System.out.println("StatusCode: " + ex.getStatusCode());
			System.out.println("ErrorCode: " + ex.getErrorCode());
			System.out.println("ErrorType: " + ex.getErrorType());
			throw ex;
		}
	}

	public static ListOrdersResponse invokeListOrders(MarketplaceWebServiceOrders client, ListOrdersRequest request) {

		try {

			ListOrdersResponse response = client.listOrders(request);

			ResponseHeaderMetadata rhmd = response.getResponseHeaderMetadata();

			System.out.println("Response:");
			System.out.println("RequestId: " + rhmd.getRequestId());
			System.out.println("Timestamp: " + rhmd.getTimestamp());

			return response;
		} catch (MarketplaceWebServiceOrdersException ex) {

			System.out.println("Service Exception:");
			ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
			if (rhmd != null) {
				System.out.println("RequestId: " + rhmd.getRequestId());
				System.out.println("Timestamp: " + rhmd.getTimestamp());
			}
			System.out.println("Message: " + ex.getMessage());
			System.out.println("StatusCode: " + ex.getStatusCode());
			System.out.println("ErrorCode: " + ex.getErrorCode());
			System.out.println("ErrorType: " + ex.getErrorType());
			return null;
		}
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-15 LiCongCong
	 * 	删除
	 * </pre>
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public String delete(Integer id) {

		JSONObject json = new JSONObject();

		try {

			amazonorderslistsService.delete(id);
			json.put("result", "delete_success");
		} catch (Exception e) {

			logger.error(e.getMessage(), e);
			json.put("result", "delete_fail");
		}

		return json.toString();
	}

	public static ListOrderItemsResponse invokeListOrderItems(MarketplaceWebServiceOrders client,
			ListOrderItemsRequest request) {
		try {
			// Call the service.
			ListOrderItemsResponse response = client.listOrderItems(request);
			ResponseHeaderMetadata rhmd = response.getResponseHeaderMetadata();
			// We recommend logging every the request id and timestamp of every
			// call.
			System.out.println("Response:");
			System.out.println("RequestId: " + rhmd.getRequestId());
			System.out.println("Timestamp: " + rhmd.getTimestamp());
			String jsonstr = response.toJSON();
			ListOrderItems listOrderItems = JSON.parseObject(jsonstr, ListOrderItems.class);

			Orderitems oditems = listOrderItems.getListorderitemsresult().getOrderitems().get(0);

			return response;
		} catch (MarketplaceWebServiceOrdersException ex) {
			// Exception properties are important for diagnostics.
			System.out.println("Service Exception:");
			ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
			if (rhmd != null) {
				System.out.println("RequestId: " + rhmd.getRequestId());
				System.out.println("Timestamp: " + rhmd.getTimestamp());
			}
			System.out.println("Message: " + ex.getMessage());
			System.out.println("StatusCode: " + ex.getStatusCode());
			System.out.println("ErrorCode: " + ex.getErrorCode());
			System.out.println("ErrorType: " + ex.getErrorType());
			throw ex;
		}
	}

	/**
	 * 通过订单编号查询该订单的物流信息
	 * 
	 * @param orderid
	 *            订单编号
	 * @return
	 */
	@RequestMapping("/orderLogisticsInfo")
	public String orderLogisticsInfo(HttpServletRequest request) {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		String orderid = request.getParameter("orderid");
		System.err.println("orderid +++++++++++++" + orderid);

		DeliverGoods deliverGoods = deliverGoodsDao.findByOrderid(orderid == null ? null : Integer.parseInt(orderid));
		String code = "";
		String shipid = "";

		if (deliverGoods != null) {

			System.out.println(deliverGoods.getLogisticsCode());
			System.out.println(deliverGoods.getLogistics().getCode());
			code = deliverGoods.getLogistics().getCode();
			shipid = deliverGoods.getLogisticsCode();

		}

		KdniaoJsonBean pojo = logisticsInfoSearchService.searchLogisticsInfo(code, shipid);
		JSONObject json = new JSONObject();
		json.put("data", pojo);
		List<Trace> tlist = pojo.getTraces();
		
		
		if(tlist.size()==0){
			
			request.setAttribute("nowtime", df.format(new Date()));
			request.setAttribute("deliverGoods", deliverGoods);
			return "shopping/shipment/ordertnull";
		}
		
		
		
		for (Trace t : tlist) {
			System.err.println("===================================================");
			System.err.println(t.getAcceptStation());
			System.err.println(t.getAcceptTime());

		}

		int endindex = tlist.size() - 1;
		Trace trace = tlist.get(endindex);
		request.setAttribute("trace", trace);

		List<Trace> tklist = tlist.subList(0, endindex);

		Collections.reverse(tklist);
		request.setAttribute("tlist", tklist);
		request.setAttribute("deliverGoods", deliverGoods);

		return "shopping/shipment/ordert";
	}
}
